package Thread;

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {
    private static int count;

    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);//申请一个资源量

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                try {
                    semaphore.acquire();//获取资源
                    count++;
                    semaphore.release();;//释放资源
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                try {
                    semaphore.acquire();//获取资源
                    count++;
                    semaphore.release();//释放资源
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println(count);
    }
}
